package com.topdt.jbpm.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.thx.common.util.AppContext;
import com.thx.common.util.FileUtil;

public class PdfThread extends java.lang.Thread{
	private static final Log logger = LogFactory.getLog(PdfThread.class);
	String uploadFileName;
	String dstPath;
	String reFileName;
	
	public PdfThread(String uploadFileName, String dstPath, String reFileName) {
		super();
		this.uploadFileName = uploadFileName;
		this.dstPath = dstPath;
		this.reFileName = reFileName;
	}
	public String getDstPath() {
		return dstPath;
	}
	public void setDstPath(String dstPath) {
		this.dstPath = dstPath;
	}
	public String getReFileName() {
		return reFileName;
	}
	public void setReFileName(String reFileName) {
		this.reFileName = reFileName;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public void run() {
		convertFile(uploadFileName, dstPath, reFileName);
	}
	/**
	 * 
	 * @author zhangyong
	 * @date   2013-5-21 上午10:19:15 
	 * @param uploadFileName
	 * @param dstPath
	 * @param reFileName
	 */
	public void convertFile(String uploadFileName,String dstPath,String reFileName){
		String uploadPath = AppContext.getProperties("uploadPath");
		dstPath = uploadPath+dstPath;
		String fileUploadPathPdf = uploadPath+AppContext.getProperties("fileUploadPathPdf");
		if(!new File(dstPath).exists()){
			new File(dstPath).mkdirs();
		}
		if(!new File(fileUploadPathPdf).exists()){
			new File(fileUploadPathPdf).mkdirs();
		}		
		logger.info("源文件地址>>>>>>>>>>>>>>>"+dstPath);
    	//将上传的文件转换成pdf文档到对应的目录里
    	String ext = reFileName.substring(reFileName.lastIndexOf(".")+1);
		/*if(ext.equals("txt")){
			DocumentConvertUtil.txt2Pdf(dstPath,fileUploadPathPdf+"/"+reFileName.replaceFirst("txt", "pdf"));
		}else if(ext.equals("doc")){
			DocumentConvertUtil.doc2Pdf(dstPath,fileUploadPathPdf+"/"+reFileName.replaceFirst("doc", "pdf"));
		}else if(ext.equals("docx")){
			DocumentConvertUtil.doc2Pdf(dstPath,fileUploadPathPdf+"/"+reFileName.replaceFirst("docx", "pdf"));
		}else if(ext.equals("pdf")){
			CopyFileUtil.copyFile(dstPath,AppContext.getProperties("fileUploadPathPdf")+"/"+reFileName, true);
		}else if(ext.equals("ppt")){
			DocumentConvertUtil.doc2Pdf(dstPath,fileUploadPathPdf+"/"+reFileName.substring(0,reFileName.lastIndexOf("."))+".pdf");
		}else if(ext.equals("pptx")){
			DocumentConvertUtil.doc2Pdf(dstPath,fileUploadPathPdf+"/"+reFileName.substring(0,reFileName.lastIndexOf("."))+".pdf");
		}else if(ext.equals("xls")){
			DocumentConvertUtil.doc2Pdf(dstPath,fileUploadPathPdf+"/"+reFileName.replaceFirst("xls", "pdf"));
		}else if(ext.equals("xlsx")){
			DocumentConvertUtil.doc2Pdf(dstPath,fileUploadPathPdf+"/"+reFileName.replaceFirst("xlsx", "pdf"));
		}*/	    
    	//wangxufeng edit 2015-01-21
		/**
		 * 通过class路径找到上下文路径
		 * 
		 */
		String classPath = getClass().getClassLoader().getResource("").getPath();
		String[] paths = classPath.split("/");
		String contextPath = "";
		for (int i = 0; i < paths.length; i++) {
			if (i < paths.length - 2) {
				if (!paths[i].equals("")) {
					contextPath += paths[i] + "/";
				}
			}
		}    	
		String fileUploadPathHtml = "/" + contextPath + AppContext.getProperties("fileUploadPathHtml");
		String fileUploadPathImage = uploadPath+AppContext.getProperties("fileUploadPathImage");
		logger.info("html文件夹路径----->" + fileUploadPathHtml);
		if (!new File(fileUploadPathHtml).exists()) {
			new File(fileUploadPathHtml).mkdirs();
		}
		if(ext.equals("pdf")){
			try {
				for (int i = 0; i < 10; i++) {
					PdfThread.sleep(5000);
					File file = new File(fileUploadPathPdf+"/"+reFileName);
					if (!file.exists()) {
						continue;
					} else {
						break;
					}
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			FileUtil.copyFile(dstPath,uploadPath+AppContext.getProperties("fileUploadPathPdf")+"/"+reFileName, true);
		}else if("txt,odt,doc,docx,xlsx,xls,ppt,pptx".contains(ext)){//"txt,png,odt,doc,docx,xlsx,xls,ppt,pptx"
			try {
				//fjs20150326 add-------start 
				//如果文档是txt则先copy一份为odt文件
				if("txt".equals(ext)){
					try {
						String odtFilePath = dstPath.substring(0,dstPath.lastIndexOf("."))+".odt";
						File odtFile = new File(odtFilePath);
						if (!odtFile.exists()) {
								odtFile.createNewFile();
						} 
						/*BufferedInputStream read = new BufferedInputStream(new FileInputStream(dstPath));
						BufferedOutputStream bufferOut = new BufferedOutputStream(new FileOutputStream(odtFilePath), 8192);
						byte[] txtBuffer = new byte[5 * 1024];
						int index = 0;
						while ((index = read.read(txtBuffer)) > 0) {
							bufferOut.write(txtBuffer, 0, index);
						}
						bufferOut.flush();
						bufferOut.close();
						read.close();*/
						
						BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream(dstPath),"gb2312")); 
						BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(odtFilePath),System.getProperty("file.encoding")));
						System.out.println("fileEncoding："+System.getProperty("file.encoding"));
						String s = null;
						while((s = reader.readLine())!=null){
							writer.write(s);
							writer.newLine();
						}
						reader.close();
						writer.close();
						dstPath = odtFilePath;
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				//fjs20150326 add-------end
				for (int i = 0; i < 10; i++) {

					PdfThread.sleep(5000);

					File file = new File(dstPath);
					if (!file.exists()) {
						continue;
					} else {
						break;
					}
				}
				DocumentConvertUtil.doc2Pdf(dstPath, fileUploadPathPdf + "/" + reFileName.replaceFirst(ext, "pdf"));

				for (int j = 0; j < 10; j++) {
					PdfThread.sleep(5000);
					File file2 = new File(fileUploadPathPdf + "/" + reFileName.replaceFirst(ext, "pdf"));
					if (!file2.exists()) {
						continue;
					} else {
						break;
					}
				}


				// 解决txt直接转换为html文件时中文乱码的问题
				DocumentConvertUtil.doc2Pdf(dstPath, fileUploadPathHtml + "/" + reFileName.replaceFirst(ext, "html"));

				for (int j = 0; j < 10; j++) {
					PdfThread.sleep(5000);
					File file2 = new File(fileUploadPathHtml + "/" + reFileName.replaceFirst(ext, "html"));
					if (!file2.exists()) {
						continue;
					} else {
						break;
					}
				}
			} catch (InterruptedException e) {
				logger.error("转换文档附件线程休眠异常" + e);
			}		
		}	    
    	String fileUploadPathSwf = uploadPath+AppContext.getProperties("fileUploadPathSwf")+"/";
    	String exePath = AppContext.getProperties("exePath");
    	String sourceFileName = fileUploadPathPdf+"/"+reFileName.substring(0,reFileName.lastIndexOf("."))+".pdf";
    	String destName = reFileName.substring(0,reFileName.lastIndexOf("."))+".swf";
    	try {
    		Converter.convertPDF2SWF(exePath,sourceFileName,fileUploadPathSwf,destName);
    	} catch (IOException e) {
    		logger.error("转换文档附件时发生错误" + e);
    	}
	}	
	
}
